package br.com.rapidrest.chain;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import br.com.rapidrest.exception.ChainException;
import br.com.rapidrest.response.URL;

public class URLRedirectCommand implements Command {

	@Override
	public void execute(Chain chain) throws ChainException {
		BasicChainContext context = (BasicChainContext) chain.getContext();

		Object returnedValue = context.getReturnedValue();

		if (returnedValue instanceof URL) {
			URL url = (URL) returnedValue;

			String redirectURL = url.getUrl();

			HttpServletResponse response = context.getResponse();
			try {
				response.sendRedirect(redirectURL);
				return;
			} catch (IOException e) {
				throw new ChainException(e);
			}
		}
		chain.proceed();
	}

}
